const fs = require('fs')
const path = require('path')
const { execSync } = require('child_process')

// 获取当前时间
const now = new Date()
const formattedTime = now.getFullYear() + '-' +
  String(now.getMonth() + 1).padStart(2, '0') + '-' +
  String(now.getDate()).padStart(2, '0') + ' ' +
  String(now.getHours()).padStart(2, '0') + ':' +
  String(now.getMinutes()).padStart(2, '0') + ':' +
  String(now.getSeconds()).padStart(2, '0')

// 配置文件路径
const configPath = path.resolve(__dirname, '../config/index.js')

// 读取配置文件
let configContent = fs.readFileSync(configPath, 'utf8')

// 使用正则表达式替换时间戳
const timeRegex = /(lastCommitTime:\s*['"])[^'"]*(['"])/
configContent = configContent.replace(timeRegex, `$1${formattedTime}$2`)

// 写回文件
fs.writeFileSync(configPath, configContent)

console.log(`Updated lastCommitTime to: ${formattedTime}`)

// 运行 lint 命令（如果配置了的话）
try {
  // 检查是否有 lint 脚本
  const packageJson = JSON.parse(fs.readFileSync(path.resolve(__dirname, '../package.json'), 'utf8'))
  if (packageJson.scripts && packageJson.scripts.lint) {
    console.log('Running lint...')
    execSync('npm run lint', { cwd: path.resolve(__dirname, '../'), stdio: 'inherit' })
    console.log('Lint completed')
  } else if (packageJson.scripts && packageJson.scripts['lint-fix']) {
    console.log('Running lint-fix...')
    execSync('npm run lint-fix', { cwd: path.resolve(__dirname, '../'), stdio: 'inherit' })
    console.log('Lint-fix completed')
  }
} catch (error) {
  console.log('Lint command not found or failed, continuing...')
}

// 添加更新后的配置文件到 git staging
execSync('git add config/index.js', { cwd: path.resolve(__dirname, '../') })

// 检查是否有其他被修改的文件也需要添加
try {
  const lintedFiles = execSync('git diff --name-only', {
    cwd: path.resolve(__dirname, '../'),
    encoding: 'utf8'
  })

  if (lintedFiles.trim()) {
    console.log('Adding linted files to commit:')
    console.log(lintedFiles)
    execSync('git add .', { cwd: path.resolve(__dirname, '../') })
  }
} catch (error) {
  console.log('No additional files to add or git command failed')
}
